package com.yanqu.road.server.agent.inter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eAgentErrorCode;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.ServerMail;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.agent.AgentInterfaceMgr;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.mail.ServerMailMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;

public class AgentMail {

	public static void main(String[] args) {
		JSONObject param = new JSONObject();
		param.put("title", "1");
		param.put("msg", "2");
		param.put("annexes", "66");
		param.put("userID", "111");
		param.put("type", "4");
		new AgentMail().sendPlayerMail(param);
	}

	/**
	 * 发送单个邮件给玩家
	 */
	public String sendPlayerMail(JSONObject param) {
		JSONObject ret = AgentInterfaceMgr.getDefaultRet();

		String title = param.getString("title");
		String msg = param.getString("msg");
		String annexes = param.getString("annexes");
		String[] playerIds = param.getString("userID").split(",");

		eMailType mailType = eMailType.forValue(param.containsKey("type") ? param.getIntValue("type") : eMailType.MARKETING.getValue());
		sendMailToPlayers(title, msg, annexes, playerIds, mailType);

		AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
		return ret.toString();
	}

	/**
	 * 发送单个多语言邮件给玩家
	 */
	public String sendPlayerLanguageMail(JSONObject param) {
		JSONObject ret = AgentInterfaceMgr.getDefaultRet();
		// 奖励
		String annexes = param.getString("annexes");
		// 类型
		eMailType mailType = eMailType.forValue(param.containsKey("type") ? param.getIntValue("type") : eMailType.MARKETING.getValue());
		// 玩家id列表
		List<Long> playerIdList = StringUtils.stringToLongList(param.getString("userID"), ",");

		// 多语言
		JSONObject languageObj = param.getJSONObject("language");

		Map<String, List<Long>> playerLanguageMap = new HashMap<>();
		// 统计多个语言
		for (long playerId : playerIdList) {
			UserInfo userInfo = UserMgr.getUserInfo(playerId);
			if (userInfo != null) {
				if (!playerLanguageMap.containsKey(userInfo.getLanguage())) {
					playerLanguageMap.put(userInfo.getLanguage(), new ArrayList<>());
				}
				playerLanguageMap.get(userInfo.getLanguage()).add(playerId);
			}
		}

		for (String languageKey : playerLanguageMap.keySet()) {
			String title = "";
			String msg = "";
			if (languageObj.containsKey(languageKey)) {
				JSONObject jsonObject = languageObj.getJSONObject(languageKey);

				title = jsonObject.getString("title");
				msg = jsonObject.getString("msg");
			}
			String[] strings = new String[ playerLanguageMap.get(languageKey).size()];
			sendMailToPlayers(title, msg, annexes, StringUtils.stringToStringList(StringUtils.listToString(playerLanguageMap.get(languageKey), ","), ",").toArray(strings), mailType);
		}

		AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
		return ret.toString();
	}

	/**
	 * 全服邮件
	 */
	public String sendServerMail(JSONObject param) {
		JSONObject ret = AgentInterfaceMgr.getDefaultRet();

		String title = param.getString("title");
		String msg = param.getString("msg");
		String annexes = param.getString("annexes");
		JSONObject languageObj;
		try {
			languageObj = param.getJSONObject("language");
		} catch (Exception ex) {
			languageObj = new JSONObject();
		}
		if (languageObj == null) {
			languageObj = new JSONObject();
		}
		Set<String> appIdSet = new HashSet<>();
		try {
			int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
			if (eChannelType.Hun1.getValue() == channelId || eChannelType.MainLandBusiness.getValue() == channelId || eChannelType.MainLandInnerTest.getValue() == channelId) {
				//目前混服才有这个
				String appIdStr = param.getString("appId");
				if (!StringUtils.isNullOrEmpty(appIdStr)) {
					List<String> strings = JSON.parseArray(appIdStr, String.class);
					appIdSet.addAll(strings);
				}
			}
		} catch (Exception e) {
			ServerMailMgr.getLogger().error("send serverMail error.",e);
		}
		ServerMail serverMail = ServerMailMgr.buildServerMail(eMailType.MARKETING.getValue(), title, msg, annexes);
		serverMail.setAppIdSet(appIdSet);
		ServerMailMgr.addServerMail(serverMail, languageObj);
		GamePlayerMgr.getCopyPlayerMap().values().forEach(p -> ServerMailMgr.playerGetServerMail(p));

		AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
		return ret.toString();
	}

	private boolean sendMailToPlayers(String title, String msg, String annexes, String[] playerIds, eMailType mailType) {
		List<Long> playIdList = new ArrayList<>();
		for (int i = 0; i < playerIds.length; i++) {
			playIdList.add(Long.parseLong(playerIds[i]));
		}
		return sendMailToPlayerList(title, msg, mailType.getValue(), annexes, playIdList);
	}

	private static boolean sendMailToPlayerList(String title, String msg, short type, String annexes, List<Long> playerIds) {
		for (int i = 0; i < playerIds.size(); i++) {
			long id = playerIds.get(i);
			if(annexes == null || annexes.equals("null") || annexes.equals("")){
				MailManager.sendMail(id, type, "", msg, title);
			}else{
				MailManager.sendMail(id, type, annexes, msg, title);
			}
		}
		return true;
	}
}
